package com.coding4play.mqtt.store.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisClusterConnection;
import org.springframework.data.redis.connection.RedisClusterNode;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.KeyScanOptions;
import org.springframework.data.redis.core.ScanOptions;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Slf4j
public class RedisScan {


    public static List<String> keyScan(RedisConnectionFactory connectionFactory, Boolean isCluster, String keyMatch) {
        List<String> keyList = new ArrayList<>();

        if (isCluster) {
            log.warn("todo 集群模式实现, 未测试");
            RedisClusterConnection clusterConnection = connectionFactory.getClusterConnection();
            Iterable<RedisClusterNode> redisClusterNodes = clusterConnection.clusterGetNodes();
            Iterator<RedisClusterNode> redisClusterNodeIterator = redisClusterNodes.iterator();
            while (redisClusterNodeIterator.hasNext()) {
                ScanOptions keyScanOptions = KeyScanOptions.scanOptions().match(keyMatch).count(1000).build();
                Cursor<byte[]> cursor = clusterConnection.scan(redisClusterNodeIterator.next(), keyScanOptions);
                while (cursor.hasNext()){
                    keyList.add(new String(cursor.next()));
                }
            }
        }else {

            RedisConnection connection = connectionFactory.getConnection();

            ScanOptions keyScanOptions = KeyScanOptions.scanOptions().match(keyMatch).count(1000).build();
            Cursor<byte[]> cursor = connection.scan(keyScanOptions);
            while (cursor.hasNext()) {
                keyList.add(new String(cursor.next()));
            }
        }

        return keyList;
    }


}
